package com.shaw.workrecord.interceptor;

import com.alibaba.fastjson.JSON;
import com.shaw.workrecord.config.JWTToken;
import com.shaw.workrecord.consts.Consts;
import com.shaw.workrecord.entity.ResponseBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * https://blog.51cto.com/u_14969174/2549762
 */
@Slf4j
public class JWTFilter extends BasicHttpAuthenticationFilter {

    private int code;

    /**
     * 1.跨域处理，过滤器之前处理前置增强
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 2.preHandle 过滤器之前处理前置增强
     * 返回true则允许访问，否则跳转到onAccessDenied
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        String servletPath = ((HttpServletRequest) request).getServletPath();
        log.info("请求路径："+servletPath);

        //验证是否是有token
        if (isLoginAttempt(request, response)) {
            try {
                //进行shiro的校验
                executeLogin(request, response);
            } catch (Exception e) {
                code = Integer.parseInt(e.getMessage());
                return false;
            }
        }else {
            code = 200;
            return false;
        }
        return true;
    }

    /**
     * 3.不允许访问之后执行此方法
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        ((HttpServletResponse) response).setStatus(code);
        System.out.println(code);
        //如果返回true表示需要继续处理; 如果返回false表示该拦截器实例已经处理了,将直接返回即可
        response.setContentType("application/json;charset=utf-8");
        try {
            ResponseBean<Object> responseBean = ResponseBean.failure(1200, "token异常");
            String string = JSON.toJSONString(responseBean);
            ((HttpServletResponse) response).getWriter().print(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 4.在拦截器链执行完成后执行
     * 下一个是方法是afterCompletion; 完成处理/后置最终处理
     */
    @Override
    protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
        super.postHandle(request, response);
    }


    /**
     * 验证是否是有token
     * 有：已经登录过，需要再验证token有效性
     * 没有：用户想登录，而且请求是白名单中的login请求，放行
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader(Consts.HEADER_AUTH);
        return authorization != null;
    }
    /**
     * 如果有token,就去验证token,或者已经登录了
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String header = httpServletRequest.getHeader(Consts.HEADER_AUTH);
        JWTToken token = new JWTToken(header);
        //提交给Realm进行验证, 如没有抛出异常, 则代表验证成功返回true
        getSubject(request, response).login(token);
        return true;
    }
}

